package com.innovations.inn.service.impl;

import com.innovations.common.exception.ServiceException;
import com.innovations.common.utils.DateUtils;
import com.innovations.common.utils.uuid.IdGeneratorSnowflake;
import com.innovations.inn.domain.BusinessDemand;
import com.innovations.inn.domain.BusinessIndividual;
import com.innovations.inn.domain.Enterprise;
import com.innovations.inn.domain.OutcomesClassifyRelate;
import com.innovations.inn.domain.OutcomesTagRelate;
import com.innovations.inn.domain.ResearchInstitution;
import com.innovations.inn.domain.TagInfo;
import com.innovations.inn.domain.request.RequestBusinessDemand;
import com.innovations.inn.domain.request.RequestListFilterPreview;
import com.innovations.inn.domain.request.RequestListPreview;
import com.innovations.inn.domain.request.RequestUnitInfo;
import com.innovations.inn.domain.response.ResponseBusinessDemand;
import com.innovations.inn.domain.response.ResponseBusinessDemandList;
import com.innovations.inn.domain.response.ResponseBusinessFilterDemand;
import com.innovations.inn.domain.response.ResponseItemCount;
import com.innovations.inn.domain.response.ResponseUnitInfo;
import com.innovations.inn.mapper.BusinessDemandMapper;
import com.innovations.inn.mapper.UnitInfoMapper;
import com.innovations.inn.service.IBusinessDemandService;
import com.innovations.inn.service.IBusinessIndividualService;
import com.innovations.inn.service.IEnterpriseService;
import com.innovations.inn.service.IOutcomesClassifyRelateService;
import com.innovations.inn.service.IOutcomesTagRelateService;
import com.innovations.inn.service.IResearchInstitutionService;
import com.innovations.inn.service.ITagInfoService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static com.innovations.common.utils.MyBeanUtils.copyProperties;

/**
 * 商业需求Service业务层处理
 *
 * @author dp
 * @date 2024-08-23
 */
@Service
public class BusinessDemandServiceImpl implements IBusinessDemandService {
    @Autowired
    BusinessDemandMapper businessDemandMapper;
    @Autowired
    IdGeneratorSnowflake idGeneratorSnowflake;
    @Autowired
    IOutcomesClassifyRelateService outcomesClassifyRelateService;
    @Autowired
    IOutcomesTagRelateService outcomesTagRelateService;
    @Autowired
    ITagInfoService tagInfoService;
    @Autowired
    IResearchInstitutionService researchInstitutionService;
    @Autowired
    IBusinessIndividualService businessIndividualService;
    @Autowired
    UnitInfoMapper unitInfoMapper;
    @Autowired
    IEnterpriseService enterpriseService;

    /**
     * 查询商业需求
     *
     * @param businessDemandId 商业需求主键
     * @return 商业需求
     */
    @Override
    public ResponseBusinessDemand selectBusinessDemandByBusinessDemandId(Long businessDemandId) {
        ResponseBusinessDemand business = new ResponseBusinessDemand();
        // 获取商业需求主数据
        BusinessDemand businessDemand = businessDemandMapper.selectBusinessDemandByBusinessDemandId(businessDemandId);
        business = copyProperties(businessDemand, ResponseBusinessDemand.class);

        // 获取单位信息
        RequestUnitInfo requestUnitInfo = new RequestUnitInfo();
        requestUnitInfo.setBusinessDemandId(businessDemandId);
        if (businessDemand.getUserType() == null) {
            throw new ServiceException("用户类型不能为空!");
        }
        requestUnitInfo.setUserType(businessDemand.getUserType());

        ResponseUnitInfo unitInfo = unitInfoMapper.selectUnitInfo(requestUnitInfo);
        if (unitInfo != null) {
            business.setUnitName(unitInfo.getUnitName());
            business.setUnitArea(unitInfo.getUnitArea());
            business.setUnitContact(unitInfo.getUnitContact());
            business.setUnitPhone(unitInfo.getUnitPhone());
        }

        // 获取商业需求分类明细
        List<Long> classifyIdList = new ArrayList<>();
        List<OutcomesClassifyRelate> classifyDetail = outcomesClassifyRelateService.selectOutcomesClassifyRelateByOutcomesId(businessDemandId);
        classifyDetail.forEach(item -> {
            classifyIdList.add(item.getClassifyId());
        });
        business.setClassifyIdList(classifyIdList);

        // 获取商业需求标签明细
        List<String> tagDescList = new ArrayList<>();
        List<OutcomesTagRelate> tagDetail = outcomesTagRelateService.selectOutcomesTagRelateByOutcomesId(businessDemandId);
        tagDetail.forEach(item -> {
            tagDescList.add(item.getTagDesc());
        });
        business.setTagDescList(tagDescList);

        return business;
    }

    /**
     * 查询商业需求列表
     *
     * @param businessDemand 商业需求
     * @return 商业需求
     */
    @Override
    public List<ResponseBusinessDemandList> selectBusinessDemandList(BusinessDemand businessDemand) {
        return businessDemandMapper.selectBusinessDemandList(businessDemand);
    }

    /**
     * 查询商业需求合计
     *
     * @param businessDemand 商业需求
     * @return 商业需求合计
     */
    @Override
    public List<ResponseItemCount> selectBusinessDemandCount(BusinessDemand businessDemand) {
        return businessDemandMapper.selectBusinessDemandCount(businessDemand);
    }


    /**
     * 查询商业需求列表-预览展示
     *
     * @param businessDemand 商业需求
     * @return 商业需求集合
     */
    @Override
    public List<BusinessDemand> selectBusinessDemandPreview(RequestListPreview businessDemand) {
        return businessDemandMapper.selectBusinessDemandPreview(businessDemand);
    }

    /**
     * 查询商业需求列表-预览展示-过滤
     *
     * @param requestListPreview 科研成果列表预览入参
     * @return 科研成果集合
     */
    @Override
    public List<ResponseBusinessFilterDemand> selectBusinessDemandFilterPreview(RequestListFilterPreview requestListPreview) {
        // 提交时间校验
        if (requestListPreview.getSubmitTime() == null && requestListPreview.getDay() != null && requestListPreview.getDay() != 0) {
            requestListPreview.setSubmitTime(LocalDateTime.now().minusDays(requestListPreview.getDay()));
        }
        return businessDemandMapper.selectBusinessDemandFilterPreview(requestListPreview);
    }

    /**
     * 新增商业需求
     *
     * @param businessDemand 商业需求
     * @return 结果
     */
    @Override
    public int insertBusinessDemand(RequestBusinessDemand businessDemand) {
        // return businessDemandMapper.insertBusinessDemand(businessDemand);

        try {
            // 验证提交内容是否有 base64 数据流
            if (businessDemand.getBusinessDemandContent().contains(";base64,")) {
                throw new Exception("上传图片、视频、等文件请通过菜单栏按钮添加！");
            }

            // 保存商业需求主数据
            BusinessDemand response = copyProperties(businessDemand, BusinessDemand.class);
            businessDemandMapper.insertBusinessDemand(response);

            //region 保存商业需求分类明细
            List<OutcomesClassifyRelate> classifyRelateList = new ArrayList<>();
            // 循环添加分类明细
            for (Long classifyId : businessDemand.getClassifyIdList()) {
                OutcomesClassifyRelate outcomesClassifyRelate = new OutcomesClassifyRelate();
                outcomesClassifyRelate.setRelateId(idGeneratorSnowflake.nextId());
                outcomesClassifyRelate.setResearchOutcomesId(response.getBusinessDemandId());
                outcomesClassifyRelate.setClassifyId(classifyId);
                classifyRelateList.add(outcomesClassifyRelate);
            }
            outcomesClassifyRelateService.insertOutcomesClassifyRelateList(classifyRelateList);
            //endregion 保存商业需求分类明细

            //region 保存商业需求标签明细
            List<OutcomesTagRelate> tagRelateList = new ArrayList<>();
            // 循环添加标签明细
            for (String tagDesc : businessDemand.getTagDescList()) {
                OutcomesTagRelate outcomesTagRelate = new OutcomesTagRelate();
                // 判断标签字典是否存在
                TagInfo tagInfo = new TagInfo();
                tagInfoService.completeData(tagInfo, businessDemand.getCreateBy(), 1);
                tagInfo.setTagDesc(tagDesc);
                if (tagInfoService.selectTagInfoByTagDesc(tagInfo.getTagDesc()) == null) {
                    // 不存在则添加
                    tagInfoService.insertTagInfo(tagInfo);
                } else {
                    // 存在则获取标签id
                    outcomesTagRelate.setTagId(tagInfo.getTagId());
                }

                outcomesTagRelate.setRelateId(idGeneratorSnowflake.nextId());
                outcomesTagRelate.setResearchOutcomesId(response.getBusinessDemandId());
                outcomesTagRelate.setTagDesc(tagDesc);
                // 添加成果对应标签明细列表
                tagRelateList.add(outcomesTagRelate);
            }
            outcomesTagRelateService.insertOutcomesTagRelate(tagRelateList);
            //endregion 保存商业需求标签明细
        } catch (Exception e) {
            return 0;
        }
        return 1;
    }

    /**
     * 修改商业需求
     *
     * @param businessDemand 商业需求
     * @return 结果
     */
    @Override
    public int updateBusinessDemand(RequestBusinessDemand businessDemand) {
        try {
            // 1.保存商业需求主数据
            BusinessDemand response = copyProperties(businessDemand, BusinessDemand.class);
            businessDemandMapper.updateBusinessDemand(response);

            //region 2.保存商业需求分类明细
            // 2.1先删除
            outcomesClassifyRelateService.deleteOutcomesClassifyRelateByOutcomesId(response.getBusinessDemandId());
            // 2.2后添加
            List<OutcomesClassifyRelate> classifyRelateList = new ArrayList<>();
            // 循环添加分类明细
            for (Long classifyId : businessDemand.getClassifyIdList()) {
                OutcomesClassifyRelate outcomesClassifyRelate = new OutcomesClassifyRelate();
                outcomesClassifyRelate.setRelateId(idGeneratorSnowflake.nextId());
                outcomesClassifyRelate.setResearchOutcomesId(response.getBusinessDemandId());
                outcomesClassifyRelate.setClassifyId(classifyId);
                classifyRelateList.add(outcomesClassifyRelate);
            }
            outcomesClassifyRelateService.insertOutcomesClassifyRelateList(classifyRelateList);
            //endregion 保存商业需求分类明细

            //region 3.保存商业需求标签明细
            // 3.1先删除
            outcomesTagRelateService.deleteOutcomesTagRelateByResearchOutcomesId(response.getBusinessDemandId());
            // 3.2后添加
            List<OutcomesTagRelate> tagRelateList = new ArrayList<>();
            // 循环添加标签明细
            for (String tagDesc : businessDemand.getTagDescList()) {
                OutcomesTagRelate outcomesTagRelate = new OutcomesTagRelate();
                // 3.3判断标签字典是否存在
                TagInfo tagInfo = new TagInfo();
                tagInfoService.completeData(tagInfo, businessDemand.getCreateBy(), 1);
                tagInfo.setTagDesc(tagDesc);
                if (tagInfoService.selectTagInfoByTagDesc(tagInfo.getTagDesc()) == null) {
                    // 不存在则添加
                    tagInfoService.insertTagInfo(tagInfo);
                } else {
                    // 存在则获取标签id
                    outcomesTagRelate.setTagId(tagInfo.getTagId());
                }

                outcomesTagRelate.setRelateId(idGeneratorSnowflake.nextId());
                outcomesTagRelate.setResearchOutcomesId(response.getBusinessDemandId());
                outcomesTagRelate.setTagDesc(tagDesc);
                // 添加成果对应标签明细列表
                tagRelateList.add(outcomesTagRelate);
            }
            outcomesTagRelateService.insertOutcomesTagRelate(tagRelateList);
            //endregion 保存商业需求标签明细
        } catch (Exception e) {
            return 0;
        }
        return 1;
    }

    /**
     * 批量删除商业需求
     *
     * @param businessDemandIds 需要删除的商业需求主键
     * @return 结果
     */
    @Override
    public int deleteBusinessDemandByBusinessDemandIds(Long[] businessDemandIds) {
        return businessDemandMapper.deleteBusinessDemandByBusinessDemandIds(businessDemandIds);
    }

    /**
     * 删除商业需求信息
     *
     * @param businessDemandId 商业需求主键
     * @return 结果
     */
    @Override
    public int deleteBusinessDemandByBusinessDemandId(Long businessDemandId) {
        return businessDemandMapper.deleteBusinessDemandByBusinessDemandId(businessDemandId);
    }

    /**
     * 实体数据补全
     *
     * @param businessDemand 实体
     * @param userId         用户id
     * @param crateType      创建类型 1：新增 2：修改
     */
    @Override
    public void completeData(RequestBusinessDemand businessDemand, Long userId, Integer crateType) {
        // 标识
        if (businessDemand.getBusinessDemandId() == null) {
            businessDemand.setBusinessDemandId(idGeneratorSnowflake.nextId());
        }
        // 创建人、创建时间
        if (crateType == 1) {
            // 判断用户类型
            if (businessDemand.getUserType() == null) {
                throw new ServiceException("用户类型不能为空！");
            }
            if (businessDemand.getCreateBy() == null || "".equals(businessDemand.getCreateBy())) {
                businessDemand.setCreateBy(userId);
            }
            if (businessDemand.getCreateTime() == null) {
                businessDemand.setCreateTime(DateUtils.getNowDate());
            }
        }

        // 提交人、提交时间
        if (crateType == 2) {
            if (businessDemand.getCreateBy() != null || !"".equals(businessDemand.getCreateBy())) {
                businessDemand.setCreateBy(null);
            }
            if (businessDemand.getCreateTime() != null) {
                businessDemand.setCreateTime(null);
            }
        }
        // 逻辑删除
        if (businessDemand.getIsDeleted() == null || "".equals(businessDemand.getIsDeleted())) {
            businessDemand.setIsDeleted(0L);
        }
        // 所属科研机构
        if (businessDemand.getInstitutionId() == null) {
            //用户类型(1.个人 2.机构 3.企业)及用户id获取机构id
            if (businessDemand.getUserType() == 1) {
                // 个人机构查询
                BusinessIndividual businessIndividualNew = new BusinessIndividual();
                businessIndividualNew.setUserId(userId);
                List<BusinessIndividual> list = businessIndividualService.selectBusinessIndividualList(businessIndividualNew);
                if (list == null || list.isEmpty()) {
                    throw new ServiceException("个人用户未绑定机构，请联系管理员！");
                } else {
                    businessDemand.setInstitutionId(list.get(0).getInstitutionId());
                }
            } else if (businessDemand.getUserType() == 2) {
                ResearchInstitution researchInstitution = new ResearchInstitution();
                researchInstitution.setUserId(userId);
                List<ResearchInstitution> list = researchInstitutionService.selectResearchInstitutionList(researchInstitution);
                if (list == null || list.isEmpty()) {
                    throw new ServiceException("机构用户未绑定机构，请联系管理员！");
                } else {
                    businessDemand.setInstitutionId(list.get(0).getInstitutionId());
                }
            } else if (businessDemand.getUserType() == 3) {
                Enterprise researchInstitution = new Enterprise();
                researchInstitution.setUserId(userId);
                List<Enterprise> list = enterpriseService.selectEnterpriseList(researchInstitution);
                if (list == null || list.isEmpty()) {
                    throw new ServiceException("企业用户未绑定机构，请联系管理员！");
                } else {
                    businessDemand.setInstitutionId(list.get(0).getEnterpriseId());
                }
            }
        }
    }

}
